
<template>
  <div class="map">

    <div class="address">{{ addrContent.address }}</div>
    <div id="map-container"></div>

    <div class="search-con">
      <Input placeholder="输入关键字搜索" id="input-map" v-model="mapSearch" />
      <ul>
        <li v-for="(tip, index) in tips" :key="index" @click="selectAddr(tip.location)">
          <p>{{ tip.name }}</p>
          <p>{{ tip.district + tip.address }}</p>
        </li>
      </ul>
    </div>
    <div slot="footer" class="footer">

      <Button type="primary" :loading="loading" @click="ok">确定</Button>
    </div>

  </div>
</template>

<script>

import config from "@/config";

export default {
  name: "tdt-map",
  data() {
    return {
      wxMap: null,
      address: null,
      lat_long: null,
      config,
      showMap: false, // 地图显隐
      mapSearch: "", // 地图搜索
      map: null, // 初始化地图
      autoComplete: null, // 初始化搜索方法
      geocoder: null, // 初始化地理、坐标转化
      positionPicker: null, // 地图拖拽选点
      tips: [], //搜索关键字列表
      addrContent: {}, // 回显地址信息
      loading: false, // 加载状态
      localsearch:null,
    };
  },
  mounted() {
    this.initwxMap();

  },
  watch: {
    mapSearch: function (val) {
      this.searchOfMap(val);
    },
  },
  methods:{
    ok(){

    },

    selectAddr(location) {
      // 选择坐标
      if (!location) {
        this.$Message.warning("请选择正确点位");
        return false;
      }
      const lnglat = [location.lng, location.lat];
      var winHtml = "名称:" + "name" + "<br/>地址:" + location.address;
      //this.showPosition(marker,winHtml)

    },
     getPosition(){
       return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function (position) {
            let latitude = position.coords.latitude
            let longitude = position.coords.longitude
            let data = {
              latitude: latitude,
              longitude: longitude
            }
            resolve(data)
          }, function () {
            reject(arguments)
          })
        } else {
          reject('你的浏览器不支持当前地理位置信息获取')
        }
      });
    },

    // 初始化天地图
    initwxMap() {
      let that=this;
      let latitude=108.94318;
      let longitude=34.25722;
    //   this.$getLocation().then(location =>{
    //     console.log(location.city);
    //   }).catch(error =>{
    //     console.log(error);
    //   });

      this.getPosition().then(result => {
        // 返回结果示例：
        // {latitude: 30.318030999999998, longitude: 120.05561639999999}
        // 一般小数点后只取六位，所以用以下代码搞定
        let queryData = {
          longitude: String(result.longitude).match(/\d+\.\d{0,6}/)[0],
          latitude: String(result.latitude).match(/\d+\.\d{0,6}/)[0],
          channelType: '00'
        }
        console.log(queryData)
        // 以下放置获取坐标后你要执行的代码:
        // ...
      }).catch(err => {
        console.log(err)
      })


      // vue项目需要先声明 T = window.T
      let T = window.T;
      this.wxMap = new T.Map('map-container'); // div的id

      // 传参中心点经纬度，以及放大程度，最小1，最大18
      this.wxMap.centerAndZoom(new T.LngLat(latitude, longitude), 18);
      var cp = new T.CoordinatePickup(this.wxMap, {
        callback: this.getLngLat
      });
      cp.addEvent();


      //鹰眼
    //   let miniMap = new T.Control.OverviewMap({
    //     isOpen: true,
    //     size: new T.Point(150, 150)
    //   });
    //   this.wxMap.addControl(miniMap);


    },

    searchOfMap(val) {
      let T = window.T;
      let that = this;
      //创建搜索对象
      let localsearch =  new T.LocalSearch(this.wxMap, {
        pageCapacity: 10,
        onSearchComplete:function (result){
          that.pois(result.getPois());
        }
      });
      localsearch.search(val);

      // this.autoComplete.search(val, function (status, result) {
      //   // 搜索成功时，result即是对应的匹配数据
      //   if (status == "complete" && result.info == "OK") {
      //     that.tips = result.tips;
      //   } else {
      //     that.tips = [];
      //   }
      // });
    },

    //解析点数据结果
    pois(obj) {
        if (obj) {
            if (obj.length>0) {
              that.tips = obj;
            } else {
              that.tips = [];
            }
          let T = window.T;
            //显示搜索列表
            var divMarker = document.createElement("div");
            //坐标数组，设置最佳比例尺时会用到
            var zoomArr = [];
            for (var i = 0; i < obj.length; i++) {
                //闭包
                (function (i) {
                    //名称
                    var name = obj[i].name;
                    //地址
                    var address = obj[i].address;
                    //坐标
                    var lnglatArr = obj[i].lonlat.split(",");
                    var lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1]);

                    var winHtml = "名称:" + name + "<br/>地址:" + address;

                    //创建标注对象
                    var marker = new T.Marker(lnglat);
                    //地图上添加标注点
                    map.addOverLay(marker);
                    //注册标注点的点击事件
                    var markerInfoWin = new T.InfoWindow(winHtml, {autoPan: true});
                    marker.addEventListener("click", function () {
                        marker.openInfoWindow(markerInfoWin);
                    });
                    zoomArr.push(lnglat);
                })(i);
            }
            //显示地图的最佳级别
            map.setViewport(zoomArr);

        }
    },

    //显示信息框
    showPosition(marker, winHtml) {
        var T = window.T;
        var markerInfoWin = new T.InfoWindow(winHtml, {autoPan: true});
        marker.openInfoWindow(markerInfoWin);
    },

    getLngLat(lnglat) {
      let T = window.T;
      const x = lnglat.lng.toFixed(6);
      const y = lnglat.lat.toFixed(6);
      this.wxMap.clearOverLays(); // 清空原来的标注点
      let point = new T.LngLat(x, y);
      let marker = new T.Marker(point);
      this.wxMap.addOverLay(marker); // 添加标注点
      let geocoder = new T.Geocoder();
      geocoder.getLocation(new T.LngLat(x, y), (result) => {
        this.address = result.getAddress();
        console.log("address="+this.address,"lat_long="+this.lat_long)
        var winHtml = "名称:" + "name" + "<br/>地址:" + this.address;
        this.showPosition(marker,winHtml)

      });
    },
    // 根据经纬度获取地址
    async getGeocoderFun(lon, lat) {
      let T = window.T;
      let geocoder = new T.Geocoder();
      geocoder.getLocation(new T.LngLat(lon, lat), (result) => {
        this.address = result.getAddress();
        this.lat_long = lon + ',' + lat;
        console.log("address="+this.address,"lat_long="+this.lat_long)

      });
    }

  }

}
</script>

<style lang="scss" scoped>
#map-container {
  width: 500px;
  height: 400px;
}

.search-con {
  position: absolute;
  right: 20px;
  top: 64px;
  width: 260px;

  ul {
    width: 260px;
    height: 360px;
    overflow: scroll;

    li {
      padding: 5px;

      p:nth-child(2) {
        color: #999;
        font-size: 12px;
      }

      &:hover {
        background-color: #eee;
        cursor: pointer;
      }
    }
  }
}

.address {
  margin-bottom: 10px;
  // color: $theme_color;
  font-weight: bold;
}

.footer {
  text-align: right;
  margin: 10px 0;
}
</style>
